<template>
  <el-card>
    <!-- 分类依据选择器 -->
    <div style="width: 110px; margin-bottom: 10px; margin-right: 10px; float: left">
      <el-select v-model="selector">
        <el-option value="1" label="按分区" />
        <el-option value="2" label="按标签" />
      </el-select>
    </div>
    <!-- 分区选择器 -->
    <div v-if="selector == 1">
      <el-cascader
        ref="cascader"
        v-model="selectedZone"
        :options="zones"
        :props="{ expandTrigger: 'hover', emitPath: false, checkStrictly: true }"
        @change="handleZoneChange"
        placeholder="选择分区"
        style="width: 180px"
      >
      </el-cascader>
    </div>

    <div v-else-if="selector == 2">
      <el-input
        v-model="inputTag"
        placeholder="请输入标签"
        style="width: 180px; margin-right: 5px"
        clearable
        @keyup.enter="handleTagChange()"
      />
      <el-button type="primary" @click="handleTagChange()">查询</el-button>
    </div>

    <!-- 数据概览卡片 -->
    <div class="stats-overview" style="margin-bottom: 20px">
      <el-row :gutter="16">
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-title">UP主总数</div>
            <div class="stat-value">{{ totalUpCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-title">平均粉丝数</div>
            <div class="stat-value">{{ formatNumber(totalFollowers) }}</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-title">平均播放量</div>
            <div class="stat-value">{{ formatNumber(totalViews) }}</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-title">平均点赞数</div>
            <div class="stat-value">{{ formatNumber(totalLikes) }}</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-title">平均投币数</div>
            <div class="stat-value">{{ formatNumber(totalCoins) }}</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-title">平均视频数</div>
            <div class="stat-value">{{ formatNumber(totalVideos) }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-tabs v-model="activeTab" v-loading="loading" @tab-change="handleTabChange">
      <!-- 热门UP主表格 -->
      <el-tab-pane label="UP主列表" name="table">
        <!-- 表格内容 -->
        <div class="table-controls" style="margin-bottom: 10px">
          排序依据：
          <el-select v-model="sortMetric" @change="sortUpData" placeholder="排序依据" style="width: 180px">
            <el-option v-for="item in sortMetrics" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>

          <el-input
            v-model="searchKeyword"
            placeholder="搜索UP主名称"
            style="width: 200px; margin-left: 15px"
            @input="handleSearch"
            clearable
          />
        </div>

        <el-table :data="pagedData" style="width: 100%" :row-class-name="tableRowClassName">
          <el-table-column label="排名" min-width="60">
            <template #default="{ $index }">
              <span :class="getRankClass($index + 1 + (currentPage - 1) * pageSize)">
                {{ $index + 1 + (currentPage - 1) * pageSize }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="UP主信息" min-width="180">
            <template #default="{ row }">
              <div class="up-info">
                <img :src="row.face" :alt="row.name" class="up-avatar" referrerpolicy="no-referrer" />
                <div class="up-name-container">
                  <div class="up-name">
                    <el-link :href="`https://space.bilibili.com/${row.mid}`" target="_blank" type="primary">
                      {{ row.name }}
                    </el-link>
                  </div>
                  <div class="up-sex">{{ row.sex || '未知' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="粉丝数" min-width="100">
            <template #default="{ row }">{{ formatNumber(row.follower) }}</template>
          </el-table-column>
          <el-table-column label="总播放" min-width="100">
            <template #default="{ row }">{{ formatNumber(row.totalView) }}</template>
          </el-table-column>
          <el-table-column label="平均播放" min-width="100">
            <template #default="{ row }">{{ formatNumber(row.view) }}</template>
          </el-table-column>
          <el-table-column label="平均点赞" min-width="100">
            <template #default="{ row }">{{ formatNumber(row.like) }}</template>
          </el-table-column>
          <el-table-column label="平均投币" min-width="100">
            <template #default="{ row }">{{ formatNumber(row.coin) }}</template>
          </el-table-column>
          <el-table-column label="平均收藏" min-width="100">
            <template #default="{ row }">{{ formatNumber(row.favorite) }}</template>
          </el-table-column>
          <el-table-column label="视频数" min-width="80">
            <template #default="{ row }">{{ row.count }}</template>
          </el-table-column>
          <el-table-column label="操作" min-width="120">
            <template #default="{ row }">
              <el-button size="small" @click="showUpDetail(row)">详情分析</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="filteredData.length"
          layout="prev, pager, next, jumper, sizes"
          :page-sizes="[10, 15, 20, 50]"
          style="margin-top: 16px; text-align: right"
          @size-change="handlePageSizeChange"
        />
      </el-tab-pane>

      <!-- 数据可视化图表 -->
      <el-tab-pane label="数据分布" name="chart">
        <div class="chart-container">
          <div
            v-if="activeTab === 'chart'"
            ref="followerChart"
            class="chart-item"
            :style="{ width: '100%', height: '500px' }"
          ></div>
          <div
            v-if="activeTab === 'chart'"
            ref="performanceChart"
            class="chart-item"
            :style="{ width: '100%', height: '500px' }"
          ></div>
        </div>
      </el-tab-pane>

      <!-- UP主详情分析 -->
      <el-tab-pane label="UP主详情" name="detail" v-if="selectedUp !== null">
        <!-- 详情内容 -->
        <div class="up-detail-header">
          <img :src="selectedUp.face" :alt="selectedUp.name" class="detail-avatar" />
          <div class="detail-info">
            <h2>
              <el-link :href="`https://space.bilibili.com/${selectedUp.mid}`" target="_blank" type="primary">
                {{ selectedUp.name }}
              </el-link>
            </h2>
            <div class="detail-meta">
              <span class="meta-item">性别: {{ selectedUp.sex || '未知' }}</span>
              <span class="meta-item">视频数: {{ selectedUp.count }}</span>
              <span class="meta-item">粉丝数: {{ formatNumber(selectedUp.follower) }}</span>
            </div>
          </div>
        </div>

        <div class="detail-stats">
          <el-row :gutter="16">
            <el-col :span="8">
              <el-card class="detail-stat-card">
                <div class="stat-title">平均播放</div>
                <div class="stat-value">{{ formatNumber(selectedUp.view) }}</div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="detail-stat-card">
                <div class="stat-title">平均点赞</div>
                <div class="stat-value">{{ formatNumber(selectedUp.like) }}</div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="detail-stat-card">
                <div class="stat-title">平均投币</div>
                <div class="stat-value">{{ formatNumber(selectedUp.coin) }}</div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 月度数据图表 -->
        <div v-if="upMonthlyData.length > 0" class="monthly-chart-container">
          <h3 style="text-align: center; margin: 20px 0">{{ selectedUp.name }} 月度数据趋势</h3>
          <div ref="upMonthlyChart" class="monthly-chart" :style="{ width: '100%', height: '500px' }"></div>
        </div>
        <div v-else-if="loadingMonthlyData" style="text-align: center; padding: 40px 0">
          <el-loading
            v-model="loadingMonthlyData"
            text="正在加载月度数据..."
            spinner="el-icon-loading"
            background="transparent"
          >
          </el-loading>
        </div>
        <div v-else style="text-align: center; padding: 40px 0">
          <p>暂无该UP主的月度数据</p>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script setup>
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import * as echarts from 'echarts'
import { useApi } from '@/composables/useApi'
import partitionData from '@/assets/partition.json'

const http = useApi()

// 分类依据
const selector = ref('1')

// 分区相关
const zones = partitionData
const selectedZone = ref(0) // 默认全站

// 图表相关
const followerChart = ref(null)
const performanceChart = ref(null)
const upMonthlyChart = ref(null) // 改为月度图表
let myFollowerChart = null
let myPerformanceChart = null
let myUpMonthlyChart = null // 改为月度图表实例

// 数据相关
const upData = ref([])
const filteredData = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const inputTag = ref('')

// 分页和排序
const currentPage = ref(1)
const pageSize = ref(15) // 默认15条每页
const activeTab = ref('table')
const sortMetrics = [
  { value: 'follower', label: '粉丝数' },
  { value: 'totalView', label: '总播放量' },
  { value: 'view', label: '平均播放量' },
  { value: 'like', label: '平均点赞数' },
  { value: 'coin', label: '平均投币数' },
  { value: 'favorite', label: '平均收藏数' },
  { value: 'count', label: '视频数' },
]
const sortMetric = ref('follower')

// 详情页相关
const selectedUp = ref(null)
const upMonthlyData = ref([]) // 存储UP主月度数据
const loadingMonthlyData = ref(false) // 月度数据加载状态

// 统计数据
const totalUpCount = ref(0)
const totalFollowers = ref(0)
const totalViews = ref(0)
const totalLikes = ref(0)
const totalCoins = ref(0)
const totalVideos = ref(0)

// 分页数据
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredData.value.slice(start, start + pageSize.value)
})

// 加载UP主数据
const loadUpData = async (categorizer) => {
  try {
    loading.value = true
    const res =
      categorizer === 'tag'
        ? await http.get('/author/getHotAuthorByTag', {
            params: { tag: inputTag.value },
          })
        : await http.get('/author/getHotAuthor', {
            params: { tid: selectedZone.value },
          })

    // 验证响应结构
    if (res && res.code === 200 && Array.isArray(res.data)) {
      upData.value = res.data || []
      calculateTotalStats()
      sortUpData()
      // 只有在当前标签是图表时才渲染，优化性能
      if (activeTab.value === 'chart') {
        renderCharts()
      }
    } else {
      console.error('无效的响应格式', res)
      upData.value = []
      calculateTotalStats()
      sortUpData()
    }
  } catch (e) {
    console.error('获取UP主数据失败', e)
    upData.value = []
    calculateTotalStats()
    sortUpData()
  } finally {
    loading.value = false
  }
}

// 计算统计数据
const calculateTotalStats = () => {
  // 首先定义len变量，获取数据长度
  const len = upData.value.length

  // 计算每个up总播放数
  upData.value.forEach((d) => {
    d.totalView = d.view * d.count
  })

  totalUpCount.value = len

  totalFollowers.value =
    len > 0 ? Math.round(upData.value.reduce((sum, up) => sum + (Number(up.follower) || 0), 0) / len) : 0
  totalViews.value = len > 0 ? Math.round(upData.value.reduce((sum, up) => sum + (Number(up.view) || 0), 0) / len) : 0
  totalLikes.value = len > 0 ? Math.round(upData.value.reduce((sum, up) => sum + (Number(up.like) || 0), 0) / len) : 0
  totalCoins.value = len > 0 ? Math.round(upData.value.reduce((sum, up) => sum + (Number(up.coin) || 0), 0) / len) : 0
  totalVideos.value = len > 0 ? Math.round(upData.value.reduce((sum, up) => sum + (Number(up.count) || 0), 0) / len) : 0
}

// 处理分区变化
const handleZoneChange = () => {
  currentPage.value = 1
  loadUpData('zone')
}

// 处理标签变化
const handleTagChange = () => {
  currentPage.value = 1
  sortMetric.value = 'totalView'
  loadUpData('tag')
}

// 排序UP主数据
const sortUpData = () => {
  filteredData.value = [...upData.value].sort((a, b) => {
    const valueA = a[sortMetric.value] || 0
    const valueB = b[sortMetric.value] || 0
    return valueB - valueA
  })
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  if (!searchKeyword.value.trim()) {
    filteredData.value = [...upData.value].sort((a, b) => {
      const valueA = a[sortMetric.value] || 0
      const valueB = b[sortMetric.value] || 0
      return valueB - valueA
    })
  } else {
    const keyword = searchKeyword.value.trim().toLowerCase()
    filteredData.value = upData.value
      .filter((up) => up.name.toLowerCase().includes(keyword))
      .sort((a, b) => {
        const valueA = a[sortMetric.value] || 0
        const valueB = b[sortMetric.value] || 0
        return valueB - valueA
      })
  }
}

// 显示UP主详情并加载月度数据
const showUpDetail = async (up) => {
  if (!up || !up.mid) {
    console.error('无效的UP主数据', up)
    return
  }
  selectedUp.value = up
  activeTab.value = 'detail'
  // 清空之前的数据
  upMonthlyData.value = []

  // 加载月度数据
  await loadUpMonthlyData(up.mid)

  // 使用nextTick确保DOM已更新
  nextTick(() => {
    renderUpMonthlyChart()
  })
}

// 加载UP主月度数据
const loadUpMonthlyData = async (mid) => {
  if (!mid) return

  loadingMonthlyData.value = true
  try {
    const res = await http.get('/author/getDataMonthly', {
      params: { mid },
    })

    if (res && res.code === 200 && Array.isArray(res.data)) {
      // 按月份排序
      upMonthlyData.value = res.data.sort((a, b) => {
        return new Date(a.month) - new Date(b.month)
      })
    }
  } catch (e) {
    console.error('获取UP主月度数据失败', e)
    upMonthlyData.value = []
  } finally {
    loadingMonthlyData.value = false
  }
}

// 格式化数字（万/千单位）
const formatNumber = (num) => {
  if (typeof num !== 'number') {
    num = Number(num)
    if (isNaN(num)) return '0'
  }

  if (num >= 100000000) {
    return (num / 100000000).toFixed(1) + '亿'
  } else if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex < 3) {
    return 'top-rank-row'
  }
  return ''
}

// 获取排名样式
const getRankClass = (rank) => {
  if (rank === 1) return 'rank-1'
  if (rank === 2) return 'rank-2'
  if (rank === 3) return 'rank-3'
  return ''
}

// 处理标签页切换
const handleTabChange = (tabName) => {
  // 当切换到图表标签时才渲染图表，避免不必要的渲染
  if (tabName === 'chart' && upData.value.length > 0) {
    // 增加延迟确保DOM完全渲染
    setTimeout(() => {
      nextTick(() => {
        renderCharts()
      })
    }, 100)
  } else if (tabName === 'detail' && selectedUp.value && upMonthlyData.value.length > 0) {
    nextTick(() => {
      renderUpMonthlyChart()
    })
  }
}

// 处理每页条数变化
const handlePageSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1 // 重置到第一页
}

// 渲染所有图表
const renderCharts = () => {
  renderFollowerChart()
  renderPerformanceChart()
}

// 渲染粉丝分布图表
const renderFollowerChart = () => {
  if (!followerChart.value) {
    console.warn('粉丝分布图表容器不存在')
    return
  }

  // 确保容器有尺寸
  const container = followerChart.value
  if (!container || container.clientWidth === 0 || container.clientHeight === 0) {
    console.warn('粉丝分布图表容器尺寸无效')
    return
  }

  // 强制刷新尺寸
  container.style.width = '100%'
  container.style.height = '500px'
  container.offsetHeight // 触发重排

  // 销毁已有实例
  if (myFollowerChart) {
    myFollowerChart.dispose()
  }

  // 初始化图表实例
  myFollowerChart = echarts.init(container)

  // 设置主题色
  const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de']

  // 按粉丝数分组
  const followerGroups = [
    { name: '1万以下', count: 0 },
    { name: '1-10万', count: 0 },
    { name: '10-50万', count: 0 },
    { name: '50-100万', count: 0 },
    { name: '100-500万', count: 0 },
    { name: '500万以上', count: 0 },
  ]

  // 处理数据
  if (upData.value.length > 0) {
    upData.value.forEach((up) => {
      // 确保follower是有效的数字
      let followers = 0
      if (typeof up.follower === 'string') {
        followers = parseFloat(up.follower.replace(/,/g, '')) || 0
      } else if (typeof up.follower === 'number') {
        followers = up.follower
      }

      // 正确的分组逻辑
      if (followers < 10000) {
        followerGroups[0].count++
      } else if (followers < 100000) {
        followerGroups[1].count++
      } else if (followers < 500000) {
        followerGroups[2].count++
      } else if (followers < 1000000) {
        followerGroups[3].count++
      } else if (followers < 5000000) {
        followerGroups[4].count++
      } else {
        followerGroups[5].count++
      }
    })
  }

  // 图表配置
  const option = {
    color: colors,
    title: {
      text: 'UP主粉丝数量分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
      },
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ddd',
      borderWidth: 1,
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: followerGroups.map((group) => group.name),
    },
    series: [
      {
        name: '粉丝数量',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {c} ({d}%)',
        },
        labelLine: {
          show: true,
        },
        data: followerGroups.map((group) => ({
          name: group.name,
          value: group.count,
        })),
        stillShowZeroSum: true,
      },
    ],
  }

  // 设置图表选项
  myFollowerChart.setOption(option)

  // 绑定窗口大小变化事件
  const handleResize = () => {
    myFollowerChart.resize()
  }

  window.addEventListener('resize', handleResize)

  // 清理函数
  return () => {
    window.removeEventListener('resize', handleResize)
  }
}

// 渲染表现对比图表
const renderPerformanceChart = () => {
  if (!performanceChart.value) return

  // 确保容器有尺寸
  const container = performanceChart.value
  if (!container || container.clientWidth === 0 || container.clientHeight === 0) {
    console.warn('表现对比图表容器尺寸无效')
    return
  }

  // 销毁已有实例
  if (myPerformanceChart) {
    myPerformanceChart.dispose()
  }

  // 初始化图表
  myPerformanceChart = echarts.init(container)

  // 取前10名UP主进行对比
  const topUps = [...upData.value].sort((a, b) => (b.follower || 0) - (a.follower || 0)).slice(0, 10)

  // 使用渐变色增强视觉效果
  const followerColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: '#FB7299' },
    { offset: 1, color: '#F75990' },
  ])

  const viewColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: '#23ADE5' },
    { offset: 1, color: '#1890FF' },
  ])

  const likeColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: '#722ED1' },
    { offset: 1, color: '#5B21B6' },
  ])

  const option = {
    color: ['#FB7299', '#23ADE5', '#722ED1'], // 粉色、蓝色、紫色
    title: {
      text: 'TOP 10 UP主数据对比',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba(0, 0, 0, 0.05)',
        },
      },
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ddd',
      borderWidth: 1,
      textStyle: { color: '#333' },
      boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
    },
    legend: {
      data: ['粉丝数', '平均播放', '平均点赞'],
      top: 30,
      textStyle: { color: '#666' },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: topUps.map((up) => up.name),
      axisLabel: {
        rotate: 45,
        interval: 0,
        color: '#666',
      },
      axisLine: {
        lineStyle: {
          color: '#eee',
        },
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: {
      type: 'log',
      name: '数量',
      nameLocation: 'start',
      nameGap: 30,
      nameTextStyle: {
        color: '#666',
      },
      axisLine: {
        show: false,
      },
      splitLine: {
        lineStyle: {
          color: '#f5f5f5',
        },
      },
      axisLabel: {
        color: '#666',
      },
    },
    series: [
      {
        name: '粉丝数',
        type: 'bar',
        data: topUps.map((up) => up.follower || 0),
        barWidth: '25%',
        itemStyle: {
          borderRadius: [4, 4, 0, 0],
          color: followerColor,
        },
      },
      {
        name: '平均播放',
        type: 'bar',
        data: topUps.map((up) => up.view || 0),
        barWidth: '25%',
        itemStyle: {
          borderRadius: [4, 4, 0, 0],
          color: viewColor,
        },
      },
      {
        name: '平均点赞',
        type: 'bar',
        data: topUps.map((up) => up.like || 0),
        barWidth: '25%',
        itemStyle: {
          borderRadius: [4, 4, 0, 0],
          color: likeColor,
        },
      },
    ],
  }

  myPerformanceChart.setOption(option)
}

// 渲染UP主月度数据图表（复用标签月度图表逻辑）
const renderUpMonthlyChart = () => {
  if (!upMonthlyChart.value || !upMonthlyData.value.length) return

  // 确保容器有尺寸
  const container = upMonthlyChart.value
  if (!container || container.clientWidth === 0 || container.clientHeight === 0) {
    console.warn('UP主月度图表容器尺寸无效')
    return
  }

  // 销毁已有实例
  if (myUpMonthlyChart) {
    myUpMonthlyChart.dispose()
  }

  // 初始化图表
  myUpMonthlyChart = echarts.init(container)

  // 指标配置（与标签月度图表保持一致）
  const metrics = [
    { key: 'view', name: '播放量' },
    { key: 'danmaku', name: '弹幕数' },
    { key: 'reply', name: '评论数' },
    { key: 'like', name: '点赞数' },
    { key: 'coin', name: '投币数' },
    { key: 'favorite', name: '收藏数' },
    { key: 'count', name: '视频数' },
  ]

  const months = upMonthlyData.value.map((item) => item.month)

  // 更精细的指标分组，每组单独Y轴
  const yAxisGroups = [
    { indices: [0], name: '播放量', color: '#337ab7' }, // 播放量
    { indices: [1], name: '弹幕数', color: '#5cb85c' }, // 单独弹幕
    { indices: [2], name: '评论数', color: '#f0ad4e' }, // 单独评论
    { indices: [3, 4, 5], name: '三连量', color: '#d9534f' }, // 点赞、投币、收藏
    { indices: [6], name: '视频数', color: '#5bc0de' }, // 单独视频数
  ]

  // 计算每组数据的最大值，用于优化坐标轴范围
  const groupMaxValues = yAxisGroups.map((group) => {
    return Math.max(
      ...group.indices.flatMap((idx) => {
        const metricKey = metrics[idx].key
        return upMonthlyData.value.map((item) => item[metricKey])
      }),
    )
  })

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      data: metrics.map((m) => m.name),
      top: 10,
      left: 'center',
      width: '90%',
      type: 'scroll',
      orient: 'horizontal',
      padding: [5, 0],
      itemGap: 15,
      pageButtonItemGap: 5,
      pageButtonGap: 10,
    },
    grid: {
      top: '15%',
      left: '8%',
      right: '18%',
      bottom: '5%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: months,
    },
    yAxis: yAxisGroups.map((group, index) => {
      // 动态计算坐标轴最大值，留10%余量使趋势更明显
      const maxVal = groupMaxValues[index]
      const axisMax = maxVal > 0 ? Math.ceil(maxVal * 1.1) : 100

      return {
        type: 'value',
        name: group.name,
        position: index === 0 ? 'left' : 'right',
        offset: index > 1 ? (index - 1) * 80 : 0, // 右侧轴偏移
        axisLine: { lineStyle: { color: group.color } },
        axisLabel: {
          formatter: (value) => {
            if (value >= 10000) return (value / 10000).toFixed(1) + '万'
            if (value >= 1000) return (value / 1000).toFixed(1) + 'k'
            return value
          },
        },
        max: axisMax, // 设置坐标轴最大值
        splitLine: { show: index === 0 }, // 只显示第一个Y轴的网格线
      }
    }),
    series: metrics.map((metric, metricIndex) => {
      const yAxisIndex = yAxisGroups.findIndex((group) => group.indices.includes(metricIndex))

      return {
        name: metric.name,
        type: metric.name === '视频数' ? 'bar' : 'line',
        data: upMonthlyData.value.map((item) => item[metric.key]),
        smooth: true,
        yAxisIndex,
        lineStyle: { width: 2.5 },
        itemStyle: { radius: 4 },
        emphasis: {
          scale: true,
          itemStyle: { shadowBlur: 10 },
        },
      }
    }),
    animation: true,
    animationDuration: 1200,
  }

  myUpMonthlyChart.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  if (myFollowerChart) myFollowerChart.resize()
  if (myPerformanceChart) myPerformanceChart.resize()
  if (myUpMonthlyChart) myUpMonthlyChart.resize()
}

// 页面挂载时加载数据
onMounted(() => {
  loadUpData()
  window.addEventListener('resize', handleResize)

  // 组件卸载时清理
  return () => {
    window.removeEventListener('resize', handleResize)
    if (myFollowerChart) myFollowerChart.dispose()
    if (myPerformanceChart) myPerformanceChart.dispose()
    if (myUpMonthlyChart) myUpMonthlyChart.dispose()
  }
})

// 监听数据变化，只在当前是图表标签时重新渲染
watch(upData, () => {
  if (activeTab.value === 'chart') {
    renderCharts()
  }
})

// 监听月度数据变化，重新渲染图表
watch(upMonthlyData, () => {
  if (activeTab.value === 'detail') {
    renderUpMonthlyChart()
  }
})
</script>

<style scoped>
/* 基础样式与布局 */
.stats-overview {
  margin: 15px 0 25px;
}

.table-controls {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 15px;
}

.chart-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
}

/* 卡片样式 */
.stat-card,
.detail-stat-card {
  border-radius: 8px;
  text-align: center;
  padding: 15px 0;
  transition: all 0.3s ease;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.stat-card {
  background-color: #f8fafc;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.detail-stat-card {
  background-color: #f0f9ff;
}

.detail-stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.07);
}

/* 统计数字样式 */
.stat-title {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-value {
  font-size: 22px;
  font-weight: 600;
  color: #1e40af;
  transition: color 0.3s ease;
}

.stat-card:hover .stat-value {
  color: #3b82f6;
}

/* 表格样式 */
.up-info {
  display: flex;
  align-items: center;
}

.up-avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
  border: 2px solid #eff6ff;
  transition: transform 0.3s ease;
}

.up-info:hover .up-avatar {
  transform: scale(1.05);
}

.up-name-container {
  display: flex;
  flex-direction: column;
}

.up-name {
  font-weight: 500;
  color: #1e293b;
}

.up-sex {
  font-size: 12px;
  color: #64748b;
  margin-top: 2px;
}

/* 排名样式 */
.top-rank-row {
  background-color: #f0f9ff !important;
}

.rank-1 {
  color: #e67e22;
  font-weight: bold;
  font-size: 14px;
}

.rank-2 {
  color: #95a5a6;
  font-weight: bold;
  font-size: 14px;
}

.rank-3 {
  color: #d35400;
  font-weight: bold;
  font-size: 14px;
}

/* 图表容器样式 */
.chart-item,
.detail-chart {
  border-radius: 8px;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.chart-item {
  height: 500px;
}

.chart-item:hover,
.detail-chart:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.detail-chart {
  height: 500px;
  margin-top: 20px;
}

/* 详情页样式 */
.up-detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e2e8f0;
}

.detail-avatar {
  width: 110px;
  height: 110px;
  border-radius: 50%;
  margin-right: 20px;
  object-fit: cover;
  border: 3px solid #eff6ff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.detail-info h2 {
  margin: 0;
  color: #1e293b;
  font-size: 22px;
}

.detail-meta {
  margin-top: 12px;
  color: #64748b;
  font-size: 14px;
}

.meta-item {
  margin-right: 24px;
  display: inline-flex;
  align-items: center;
}

.meta-item::before {
  content: '•';
  margin-right: 6px;
  color: #94a3b8;
  font-size: 8px;
}

.detail-stats {
  margin-bottom: 30px;
}
</style>
